package softtech.apps.autoanswerphonecall;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class VoiceMessgeActivity extends Activity {
	/***
	 * Activity description:
	 * - This will running in background
	 * - Set speaker on
	 * - Record voice by MIC
	 * - General notification to user
	 * Functions:
	 * - private static void generateNotification(Context context, String message);
	 * - public void startRecording() ;
	 * - public void stopRecording();
	 * - public String getFilename();
	 */
	private final String AUDIO_RECORDER_FOLDER = "VoiceMessage";
	// Recording
	private final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
	private final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
	private MediaRecorder recorder = null;

	private File folder;
	private File files[];
	
	private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4,
			MediaRecorder.OutputFormat.THREE_GPP };
	private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4,
			AUDIO_RECORDER_FILE_EXT_3GP };

	private int currentFormat = 0;
	private String path_record = "";
	
	AudioManager audioManager;
	boolean recording = false;

	ArrayList<String> VoiceMessageReceived = new ArrayList<String>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_voice_messge);
		
		
		ActionBar bar = getActionBar();
		bar.setDisplayHomeAsUpEnabled(true);
		bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#2ac2d4"))); 
		
		String filepath = Environment.getExternalStorageDirectory().getPath();
		folder = new File(filepath, AUDIO_RECORDER_FOLDER);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		files = folder.listFiles();
		
		Log.d("ACTIVITY", "Activity Voice Message da duoc goi");
		
		//registerReceiver(mHandleMessageReceiver, new IntentFilter("stopRecordVoiceMessage"));
		//registerReceiver(mHandleMessageReceiver2, new IntentFilter("startRecordVoiceMessage"));
		
		
		
		/**
		 * Register broadcast to receive stop record signal
		 * */

//		
//		audioManager = (AudioManager) getApplicationContext().getSystemService(
//				Context.AUDIO_SERVICE);
//		audioManager.setMode(AudioManager.MODE_IN_CALL);
//		audioManager.setSpeakerphoneOn(true);
		
		/**
		 * Problem here
		 * */
		
//		am.setStreamVolume(AudioManager.STREAM_MUSIC,
//		am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
		
		
		/**
		 * Display all message received
		 * @param VoiceMessageReceived[]
		 * */
		
		
		if(!files.equals(null)){
			for(File a: files){
				VoiceMessageReceived.add(a.getName());
			}
			ArrayAdapter<String> mesAdapter =new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, VoiceMessageReceived);
			ListView lvAdapter = (ListView)findViewById(R.id.lvMessageReceived);
			lvAdapter.setAdapter(mesAdapter);
			
		}
		
		/**
		 * Start recording when it's called
		 * */
		startRecording();
		
		/**
		 * Running activity in background
		 * */
		moveTaskToBack(true);

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//unregisterReceiver(mHandleMessageReceiver);
		//unregisterReceiver(mHandleMessageReceiver2);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.voice_messge, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * Return the path of voice message to store
	 * 
	 * @param AUDIO_RECORDER_FOLDER
	 * */
	public String getFilename() {
		File file = folder;
		if (!file.exists()) {
			file.mkdirs();
		}

		// return (file.getAbsolutePath() + "/" + "Audio-Record-"
		// +System.currentTimeMillis() + file_exts[currentFormat]);
		return (file.getAbsolutePath() + "/" + "From-"+MyPhoneStateListener.incomingPhoneNumber
				+"-"+ System.currentTimeMillis() + file_exts[currentFormat]);
	}

	/**
	 * Start recording a incoming call with input from
	 * MediaRecorder.AudioSource.MIC
	 * 
	 * @param recorder
	 * */
	public void startRecording() {
		/**
		 * Device audio manager
		 * */
		AudioManager am = (AudioManager) getBaseContext()
				.getSystemService(Context.AUDIO_SERVICE);
		am.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
				am.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL), 0);
		
		am.setMode(AudioManager.MODE_IN_CALL);
		am.setSpeakerphoneOn(true);
		/**
		 * Recorder manager
		 * */
		recorder = new MediaRecorder();
		
        
		// recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		recorder.setOutputFormat(output_formats[currentFormat]);
		recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

		path_record = getFilename();
		recorder.setOutputFile(path_record);
		recorder.setOnErrorListener(errorListener);
		recorder.setOnInfoListener(infoListener);
		
		/**
		 * Starting
		 * */
		try {
			recorder.prepare();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		recorder.start();
		recording = true;
		
		
		Log.d("RECORD_INTENT", "Bat dau ghi am");

	}

	/**
	 * Stop a recorder and finish activity, add output file to wish list
	 * 
	 * @param recorder
	 * */
	public void stopRecording() {
		if (null != recorder && recording) {
			Log.d("RECORDING", "Stop recoding !!!! ");
			// filePath = getFilename();
			recorder.stop();
			recorder.reset();
			recorder.release();
			recorder = null;
			VoiceMessageReceived.add(getFilename());
			
		}
	}

	private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
		@Override
		public void onError(MediaRecorder mr, int what, int extra) {
			// Toast.makeText(VoiceManagerActivity.this,
			// "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
			Log.e("ERROR", "Loi trong qua trinh ghi am ");
			Log.e("ERROR", "Error: " + what + ", " + extra);
		}
	};

	private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
		@Override
		public void onInfo(MediaRecorder mr, int what, int extra) {
			// Toast.makeText(VoiceManagerActivity.this,
			// "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT)
			// .show();
		}
	};

	private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			
			Log.d("STOP","Intent filter stop");

			try {
				String result = intent.getExtras().getString("StopVoiceMessage");
				if (result.trim().equals("stopHere")) {
					stopRecording();
					generateNotification(context,"Vua moi ghi file = "+ path_record);
					Log.d("STOP","Stop record voice message here");
					finish();// finish activity
				}

			} catch (Exception e) {
			}finally{
				
				Log.d("FINISH", "Finish & exist");			
			}
		}
	};
	
	private final BroadcastReceiver mHandleMessageReceiver2 = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			
			Log.d("STOP","->Intent filter start");

			try {
				String result = intent.getExtras().getString("StartVoiceMessage");
				if (result.trim().equals("startHere")) {
					//startRecording();
					Log.d("STOP","--> Start record voice message here");	
				}

			} catch (Exception e) {
			}
		}
	};
	/*
	 * Issues a notification to inform the user that server has sent a message.
	 */
	private static void generateNotification(Context context, String message) {
		int icon = R.drawable.ic_launcher;
		long when = System.currentTimeMillis();
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(icon, message, when);

		String title = context.getString(R.string.app_name);

		Intent notificationIntent = new Intent(context, MainActivity.class);
		// set intent so it does not start a new activity
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent intent = PendingIntent.getActivity(context, 0,
				notificationIntent, 0);
		notification.setLatestEventInfo(context, title, message, intent);
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		// Play default notification sound
		// notification.defaults |= Notification.DEFAULT_SOUND;

		// Vibrate if vibrate is enabled
		// notification.defaults |= Notification.DEFAULT_VIBRATE;
		notificationManager.notify(0, notification);

	}
}
